#include "logutils.h"
#include <QDebug>
#include <QDateTime>
#include <QFile>
#include <QTextStream>
#include <QtMsgHandler>
#include <QMessageLogContext>
#include <QMutex>

void messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;
    mutex.lock();
    QString time = QDateTime::currentDateTime().toString(QString("[yyyy-MM-dd HH:mm:ss:zzz]"));
    QString mmsg;
    switch(type)
    {
    case QtDebugMsg:
        mmsg = QString("%1[Debug]:%2 (file:%3,line:%4,func:%5)").arg(time).arg(msg).arg(QString(context.file)).arg(context.line).arg(QString(context.function));
        break;
    case QtInfoMsg:
        mmsg = QString("%1[Info]:%2 (file:%3,line:%4,func:%5)").arg(time).arg(msg).arg(QString(context.file)).arg(context.line).arg(QString(context.function));
        break;
    case QtWarningMsg:
        mmsg = QString("%1[Warning]:%2 (file:%3,line:%4,func:%5)").arg(time).arg(msg).arg(QString(context.file)).arg(context.line).arg(QString(context.function));
        break;
    case QtCriticalMsg:
        mmsg = QString("%1[Critical]:%2 (file:%3,line:%4,func:%5)").arg(time).arg(msg).arg(QString(context.file)).arg(context.line).arg(QString(context.function));
        break;
    case QtFatalMsg:
        mmsg = QString("%1[Fatal]:%2 (file:%3,line:%4,func:%5)").arg(time).arg(msg).arg(QString(context.file)).arg(context.line).arg(QString(context.function));
        abort();
    }
    LogUtils::GetInstance()->saveFile(mmsg);
    mutex.unlock();
}

LogUtils* LogUtils::m_pInstance = nullptr;

LogUtils::LogUtils(QObject *parent) : QObject(parent)
{
    m_file = "/home/xll/Desktop/debtest.log";
}

LogUtils *LogUtils::GetInstance(QObject *parent)
{
    if (!m_pInstance) {
        m_pInstance = new LogUtils(parent);
    }
    return m_pInstance;
}

void LogUtils::setLogFile(const QString &filename)
{
    m_file = filename;
}

void LogUtils::saveFile(const QString &msg)
{
    QFile file(m_file);
    file.open(QIODevice::ReadWrite | QIODevice::Append);
    QTextStream stream(&file);
    stream << msg << "\r\n";
    file.flush();
    file.close();
}
